#!/usr/bin/env python3
# -*- coding: utf-8 -*-
"""
配置文件管理模块
用于保存和加载API Key、自定义音色信息等配置
"""

import json
import os
from pathlib import Path

class ConfigManager:
    """配置管理器"""
    
    def __init__(self):
        # 配置文件路径
        self.config_dir = Path("config")
        self.config_dir.mkdir(exist_ok=True)

        # 音频备份文件夹
        self.audio_backup_dir = self.config_dir / "voice_audio_backup"
        self.audio_backup_dir.mkdir(exist_ok=True)

        self.api_config_file = self.config_dir / "api_config.json"
        self.voices_config_file = self.config_dir / "custom_voices.json"
        
        # 默认配置
        self.default_api_config = {
            "siliconflow_token": "sk-zuhzlkznhhgengmmpbbynaqbmtxsuflfcwhyndqcgaepacbc",
            "last_updated": ""
        }
        
        self.default_voices_config = {
            "custom_voices": {},
            "last_sync": ""
        }
    
    def load_api_config(self):
        """加载API配置"""
        try:
            if self.api_config_file.exists():
                with open(self.api_config_file, 'r', encoding='utf-8') as f:
                    config = json.load(f)
                    # 确保有默认token
                    if not config.get("siliconflow_token"):
                        config["siliconflow_token"] = self.default_api_config["siliconflow_token"]
                    return config
            else:
                # 创建默认配置文件
                self.save_api_config(self.default_api_config)
                return self.default_api_config.copy()
        except Exception as e:
            print(f"加载API配置失败: {e}")
            return self.default_api_config.copy()
    
    def save_api_config(self, config):
        """保存API配置"""
        try:
            import time
            config["last_updated"] = time.strftime('%Y-%m-%d %H:%M:%S')
            
            with open(self.api_config_file, 'w', encoding='utf-8') as f:
                json.dump(config, f, ensure_ascii=False, indent=2)
            return True
        except Exception as e:
            print(f"保存API配置失败: {e}")
            return False
    
    def load_voices_config(self):
        """加载自定义音色配置"""
        try:
            if self.voices_config_file.exists():
                with open(self.voices_config_file, 'r', encoding='utf-8') as f:
                    return json.load(f)
            else:
                # 创建默认配置文件
                self.save_voices_config(self.default_voices_config)
                return self.default_voices_config.copy()
        except Exception as e:
            print(f"加载音色配置失败: {e}")
            return self.default_voices_config.copy()
    
    def save_voices_config(self, config):
        """保存自定义音色配置"""
        try:
            import time
            config["last_sync"] = time.strftime('%Y-%m-%d %H:%M:%S')
            
            with open(self.voices_config_file, 'w', encoding='utf-8') as f:
                json.dump(config, f, ensure_ascii=False, indent=2)
            return True
        except Exception as e:
            print(f"保存音色配置失败: {e}")
            return False
    
    def add_custom_voice(self, voice_name, voice_uri, voice_text, audio_file_path=None):
        """添加自定义音色"""
        voices_config = self.load_voices_config()

        # 备份音频文件
        backup_audio_path = None
        if audio_file_path and os.path.exists(audio_file_path):
            backup_audio_path = self.backup_audio_file(voice_name, audio_file_path)

        voices_config["custom_voices"][voice_name] = {
            "uri": voice_uri,
            "text": voice_text,
            "audio_backup": backup_audio_path,
            "created_time": __import__('time').strftime('%Y-%m-%d %H:%M:%S')
        }
        return self.save_voices_config(voices_config)

    def backup_audio_file(self, voice_name, audio_file_path):
        """备份音频文件到本地"""
        try:
            import shutil

            # 获取原文件扩展名
            file_ext = Path(audio_file_path).suffix

            # 生成备份文件名
            backup_filename = f"{voice_name}_{__import__('time').strftime('%Y%m%d_%H%M%S')}{file_ext}"
            backup_path = self.audio_backup_dir / backup_filename

            # 复制文件
            shutil.copy2(audio_file_path, backup_path)

            print(f"音频文件已备份到: {backup_path}")
            return str(backup_path)

        except Exception as e:
            print(f"备份音频文件失败: {e}")
            return None
    
    def remove_custom_voice(self, voice_name):
        """删除自定义音色"""
        voices_config = self.load_voices_config()
        if voice_name in voices_config["custom_voices"]:
            # 删除备份的音频文件
            voice_info = voices_config["custom_voices"][voice_name]
            backup_path = voice_info.get("audio_backup")
            if backup_path and os.path.exists(backup_path):
                try:
                    os.remove(backup_path)
                    print(f"已删除备份音频文件: {backup_path}")
                except Exception as e:
                    print(f"删除备份音频文件失败: {e}")

            del voices_config["custom_voices"][voice_name]
            return self.save_voices_config(voices_config)
        return False
    
    def get_custom_voices(self):
        """获取所有自定义音色"""
        voices_config = self.load_voices_config()
        return voices_config.get("custom_voices", {})
    
    def sync_voices_from_api(self, api_voices):
        """从API同步音色列表"""
        voices_config = self.load_voices_config()
        
        # 清空现有音色
        voices_config["custom_voices"] = {}
        
        # 添加API返回的音色
        for voice in api_voices:
            voice_name = voice.get('customName', voice.get('name', 'Unknown'))
            voice_uri = voice.get('uri', '')
            voice_text = voice.get('text', '')
            
            voices_config["custom_voices"][voice_name] = {
                "uri": voice_uri,
                "text": voice_text,
                "synced_time": __import__('time').strftime('%Y-%m-%d %H:%M:%S')
            }
        
        return self.save_voices_config(voices_config)
    
    def get_api_token(self):
        """获取API Token"""
        config = self.load_api_config()
        return config.get("siliconflow_token", self.default_api_config["siliconflow_token"])
    
    def set_api_token(self, token):
        """设置API Token"""
        config = self.load_api_config()
        config["siliconflow_token"] = token
        return self.save_api_config(config)
    
    def export_config(self, export_path):
        """导出配置到指定路径"""
        try:
            api_config = self.load_api_config()
            voices_config = self.load_voices_config()
            
            export_data = {
                "api_config": api_config,
                "voices_config": voices_config,
                "export_time": __import__('time').strftime('%Y-%m-%d %H:%M:%S')
            }
            
            with open(export_path, 'w', encoding='utf-8') as f:
                json.dump(export_data, f, ensure_ascii=False, indent=2)
            return True
        except Exception as e:
            print(f"导出配置失败: {e}")
            return False
    
    def import_config(self, import_path):
        """从指定路径导入配置"""
        try:
            with open(import_path, 'r', encoding='utf-8') as f:
                import_data = json.load(f)
            
            if "api_config" in import_data:
                self.save_api_config(import_data["api_config"])
            
            if "voices_config" in import_data:
                self.save_voices_config(import_data["voices_config"])
            
            return True
        except Exception as e:
            print(f"导入配置失败: {e}")
            return False
